#pragma once

#include <iostream>
#include <string>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
};

// 继承一个禁止拷贝的基类。避免有人在栈上定义智能指针进行服务端拷贝
class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t localport = glocalport)
        : _sockfd(gsockfd), _localport(localport), _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建socket文件
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd: %d\n", _sockfd);

        // 2.bind绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local)); // 先把结构体清空
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);                  // 端口号,主机序列转成网络序列
        //local.sin_addr.s_addr = inet_addr(_localip.c_str()); // 1.需要4字节ip地址 2.需要网络序列ip - 暂时
        local.sin_addr.s_addr = INADDR_ANY; // 服务器端进行任意ip地址绑定

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            // 3.服务器直接接收数据
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                // 看看客户端的ip地址和port
                //uint16_t client_port = ntohs(peer.sin_port);
                //std::string client_ip = inet_ntoa(peer.sin_addr);

                InetAddr addr(peer);
                
                inbuffer[n] = 0;
                std::cout << "[客户端:" << addr.Ip() << ":"<< addr.Port() << "]# " <<  inbuffer << std::endl;
                std::string echo_string = "[服务端返回给客户端的]# ";
                echo_string += inbuffer;

                // 4.再把这个回显字符串返回给客户端，客户端一定在peer里
                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;          // 文件描述符
    uint16_t _localport;  // 服务端的端口号
    bool _isrunning;      // 服务端的运行状态
};
